angular.module('kityminderEditor')
    .directive('importBtn', function () {
        return {
            restrict: 'E',
            templateUrl: 'ui/directive/importBtn/importBtn.html',
            scope: {
                minder: '='
            },
            replace: true,
            link: function ($scope) {
                var minder = $scope.minder;

                $scope.items = ['JSON', 'TEXT', 'MD'];
                function importText() {
                    return new Promise((resolve, reject) => {
                        var input = document.createElement('input');
                        input.type = 'file';
                        input.accept = '.md, .txt, .json';
                        input.onchange = (event) => {
                            var file = event.target.files[0];
                            var reader = new FileReader();
                            reader.onload = (event) => {
                                resolve(event.target.result);
                            };
                            reader.onerror = (error) => {
                                reject(error);
                            };
                            reader.readAsText(file);
                        };
                        input.click();
                    });
                }
                $scope.import = {
                    JSON: function () {
                        importText().then(json => {
                            minder.importData("json", json);
                        })
                    },
                    TEXT: function () {
                        importText().then(text => {
                            minder.importData("text", text);
                        })
                    },
                    MD: function () {
                        importText().then(md => {
                            minder.importData("markdown", md);
                        })
                    }
                };
            }
        }
    });